package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.dto.MaterialUsageDTO;
import com.geek.factory.entity.Material;
import com.geek.factory.result.Result;
import com.geek.factory.service.IMaterialService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 原料基础信息表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-23
 */
@RestController
@RequestMapping("/material")
@Api(tags = "后台系统的 - 原料模块")
@Slf4j
public class MaterialController {

    @Autowired
    private IMaterialService materialService;

    /**
     * 生成原料编码
     */
    private String generateMaterialCodeInternal() {
        String prefix = "M";  // M = Material
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        return prefix + dateStr + timeStr;
    }

    @ApiOperation("生成原料编码")
    @GetMapping("/generate-code")
    public Result generateMaterialCode() {
        try {
            String materialCode = generateMaterialCodeInternal();
            Map<String, String> result = new HashMap<>();
            result.put("materialCode", materialCode);
            return new Result(SuccessConstant.SUCCESS, "生成成功", result);
        } catch (Exception e) {
            log.error("生成原料编码失败", e);
            return new Result(SuccessConstant.FAIL, "生成失败");
        }
    }

    @ApiOperation("通过ID查询原料信息")
    @GetMapping("/{id}")
    public Result getMaterialById(@ApiParam("原料ID") @PathVariable Integer id) {
        Material material = materialService.getById(id);
        log.info("原料信息: {}", material);
        if (material != null) {
            return new Result(SuccessConstant.SUCCESS, "查询成功", material);
        }
        return new Result(SuccessConstant.FAIL, "原料不存在");
    }

//    @ApiOperation("新增原料")
//    @PostMapping
//    public Result addMaterial(@RequestBody Material material) {
//        boolean isSuccess = materialService.save(material);
//        log.info("新增原料: {}, 结果: {}", material, isSuccess);
//        if (isSuccess) {
//            return new Result(SuccessConstant.SUCCESS, "新增成功", material);
//        }
//        return new Result(SuccessConstant.FAIL, "新增失败");
//    }
@ApiOperation("新增原料")
@PostMapping
public Result addMaterial(@RequestBody Material material) {
    // 如果没有设置原料编码，自动生成
    if (material.getMaterialCode() == null || material.getMaterialCode().trim().isEmpty()) {
        material.setMaterialCode(generateMaterialCodeInternal());
    }

    boolean isSuccess = materialService.save(material);
    log.info("新增原料: {}, 结果: {}", material, isSuccess);
    if (isSuccess) {
        return new Result(SuccessConstant.SUCCESS, "新增成功", material);
    }
    return new Result(SuccessConstant.FAIL, "新增失败");
}

    @ApiOperation("修改原料信息")
    @PutMapping
    public Result updateMaterial(@RequestBody Material material) {
        boolean isSuccess = materialService.updateById(material);
        log.info("修改原料: {}, 结果: {}", material, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "修改成功", material);
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    @ApiOperation("根据ID删除原料")
    @DeleteMapping("/{id}")
    public Result deleteMaterial(@ApiParam("原料ID") @PathVariable Integer id) {
        boolean isSuccess = materialService.removeById(id);
        log.info("删除原料ID: {}, 结果: {}", id, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    @ApiOperation("分页查询原料列表")
    @GetMapping("/page")
    public Result getMaterialPage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize
    ) {
        Page<Material> page = materialService.page(new Page<>(pageNum, pageSize));
        Map<String, Object> data = new HashMap<>();
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }

    @ApiOperation("获取所有原料列表")
    @GetMapping("/list")
    public Result getAllMaterials() {
        List<Material> materials = materialService.list();
        return new Result(SuccessConstant.SUCCESS, "查询成功", materials);
    }

    @ApiOperation("获取原料统计数据")
    @GetMapping("/stats")
    public Result getMaterialStats() {
        try {
            // 获取原料数量
            long materialCount = materialService.count();

            Map<String, Object> stats = new HashMap<>();
            stats.put("totalMaterials", materialCount);

            return new Result(SuccessConstant.SUCCESS, "查询成功", stats);
        } catch (Exception e) {
            log.error("获取原料统计数据失败", e);
            return new Result(SuccessConstant.FAIL, "获取统计数据失败");
        }
    }

    @PostMapping("/list")
    @ApiOperation("分页查询原料列表")
    public Result getMaterialList(@RequestBody(required = false) Map<String, Object> params) {
        int current = params != null && params.get("current") != null
                ? Integer.parseInt(params.get("current").toString()) : 1;
        int size = params != null && params.get("size") != null
                ? Integer.parseInt(params.get("size").toString()) : 10;
        String keyword = params != null && params.get("keyword") != null
                ? params.get("keyword").toString() : null;

        LambdaQueryWrapper<Material> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(Material::getMaterialName, keyword)
                    .or().like(Material::getMaterialCode, keyword);
        }

        Page<Material> page = materialService.page(new Page<>(current, size), queryWrapper);

        return new Result(true, "查询成功", page);
    }

    @PostMapping("/stock")
    @ApiOperation("验证所需原料库存是否足够")
    public Result validateMaterialStock(@RequestBody List<MaterialUsageDTO> materials) {
        for (MaterialUsageDTO item : materials) {
            Material dbMaterial = materialService.getById(item.getMaterialId());
            if (dbMaterial == null) {
                return new Result(false, "原料不存在: ID=" + item.getMaterialId(), null);
            }
            if (dbMaterial.getQuantity().compareTo(item.getRequiredQuantity()) < 0) {
                return new Result(false, "原料 " + dbMaterial.getMaterialName() + " 库存不足", null);
            }
        }
        return new Result(true, "库存充足", null);
    }
}